import 'package:flutter/material.dart';
import 'package:flutter_app/api/api_service.dart';
import 'package:flutter_app/config/config.dart';
import 'package:flutter_app/datas/category_data.dart';
import 'package:flutter_app/datas/drama_data.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../models/short_film.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateMixin {
  late Future<CategoryData?> _categoryFuture;
  final ApiService _apiService = ApiService();
  late Future<DramaData?> _dramaFuture;
  int _currentTabId = 0;
  TabController? _tabController;
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _categoryFuture = _apiService.getCategoryData();
    _categoryFuture.then((categoryData) {
      if (categoryData != null && categoryData.data.isNotEmpty) {
        // 添加 "全部" 选项
        _tabController = TabController(length: categoryData.data.length + 1, vsync: this);
        _tabController?.addListener(_handleTabSelection);
        _onTabChanged(0); // 默认加载 ID 为 0 的数据
      }
    });
  }

  void _handleTabSelection() {
    if (_tabController != null && _tabController!.indexIsChanging) {
      final categoryId = _tabController!.index == 0 ? 0 : _tabController!.index - 1;
      _onTabChanged(categoryId);
    }
  }

  Future<void> _onTabChanged(int tabId) async {
    setState(() {
      _isLoading = true;
      _currentTabId = tabId;
      // 如果 tabId 为 0，加载默认数据
      final categoryId = tabId == 0 ? 0 : tabId - 1;
      _dramaFuture = _apiService.getDramaData(categoryId.toString());
      _dramaFuture.then((_) {
        setState(() {
          _isLoading = false;
        });
      });
    });
  }

  static const List<ShortFilm> shortFilms = [
    ShortFilm(
      title: '闪婚后，傅先生每天都在真香',
      thumbnailUrl: 'https://via.placeholder.com/150',
      category: '都市言情',
      episodes: 100,
    ),
    // 添加更多短剧信息
  ];

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<CategoryData?>(
      future: _categoryFuture,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return Scaffold(
            appBar: AppBar(
              title: const Text('推荐'),
              backgroundColor: Colors.white,
              elevation: 0,
            ),
            body: const Center(child: CircularProgressIndicator()),
          );
        } else if (snapshot.hasError) {
          return Scaffold(
            appBar: AppBar(
              title: const Text('推荐'),
              backgroundColor: Colors.white,
              elevation: 0,
            ),
            body: Center(child: Text('Error: ${snapshot.error}')),
          );
        } else if (snapshot.hasData) {
          final categoryData = snapshot.data!;
          final tabs = ['全部', ...categoryData.data.map((category) => category.title).toList()];
          return DefaultTabController(
            length: tabs.length,
            child: Scaffold(
              appBar: AppBar(
                title:  Text('推荐',style: TextStyle(
                  color: Colors.black,
                  fontSize: 24.sp,
                  fontWeight: FontWeight.bold,
                ),),
                backgroundColor: Colors.white,
                elevation: 0,
                bottom: PreferredSize(
                  preferredSize: const Size.fromHeight(48.0),
                  child: Align(
                    alignment: Alignment.centerLeft,
                    child: TabBar(
                      controller: _tabController,
                      isScrollable: true,
                      indicatorColor: Colors.black,
                      labelColor: Colors.black,
                      unselectedLabelColor: Colors.grey,
                      labelStyle: TextStyle(fontWeight: FontWeight.bold, fontSize: 14.sp),
                      unselectedLabelStyle: TextStyle(fontWeight: FontWeight.normal, fontSize: 14.sp),
                      indicatorPadding: EdgeInsets.zero,
                      dividerHeight: 0,
                      tabAlignment: TabAlignment.start,
                      tabs: tabs.map((tab) => Tab(text: tab)).toList(),
                      onTap: (index) {
                        final categoryId = index == 0 ? 0 : categoryData.data[index].id;
                        _onTabChanged(categoryId);
                      },
                    ),
                  ),
                ),
                actions: [
                  IconButton(
                    icon: const Icon(Icons.search, color: Colors.black),
                    onPressed: () {
                      // 搜索按钮点击事件
                      Navigator.pushNamed(context, "/search");
                    },
                  ),
                ],
              ),
              body: _isLoading
                  ? const Center(child: CircularProgressIndicator())
                  : Container(
                color: Colors.white,
                child: Center(
                  child: TabBarView(
                    controller: _tabController,
                    physics: const NeverScrollableScrollPhysics(), // 禁用 TabBarView 的滚动
                    children: tabs.map((tab) {
                      return FutureBuilder<DramaData?>(
                        future: _dramaFuture,
                        builder: (context, snapshot) {
                          if (snapshot.connectionState == ConnectionState.waiting) {
                            return const Center(child: CircularProgressIndicator());
                          } else if (snapshot.hasError) {
                            return Center(child: Text('Error: ${snapshot.error}'));
                          } else if (snapshot.hasData) {
                            final dramaData = snapshot.data!;
                            return GridView.builder(
                              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                                crossAxisCount: 3,
                                childAspectRatio: 0.6,
                                crossAxisSpacing: 5.w,
                                mainAxisSpacing: 5.h,
                              ),
                              itemCount: dramaData.data.length,
                              itemBuilder: (context, index) {
                                final drama = dramaData.data[index];
                                return Container(
                                  margin: EdgeInsets.all(4.w),
                                  decoration: BoxDecoration(
                                    color: Colors.white, // 设置背景色为白色
                                    borderRadius: BorderRadius.circular(8.0), // 设置圆角
                                    boxShadow: [
                                      BoxShadow(
                                        color: Colors.black12, // 设置阴影颜色
                                        blurRadius: 4.0, // 设置模糊半径
                                        offset: Offset(0, 4), // 设置阴影偏移
                                      ),
                                    ],
                                  ),
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Expanded(
                                        child: Stack(
                                          children: [
                                            ClipRRect(
                                              borderRadius: BorderRadius.only(
                                                topLeft: Radius.circular(8.0),
                                                topRight: Radius.circular(8.0),
                                              ),
                                              child: Image.network(
                                                baseUrl + drama.coverImg,
                                                fit: BoxFit.cover,
                                                width: double.infinity,
                                height: double.infinity,
                                                errorBuilder: (context, error, stackTrace) {
                                                  return const Icon(Icons.error);
                                                },
                                              ),
                                            ),
                                            Positioned(
                                              bottom: 8.w,
                                              right: 8.w,
                                              child: Row(
                                                children: [
                                                  Icon(
                                                    Icons.play_arrow,
                                                    color: Colors.white,
                                                    size: 12.sp,
                                                  ),
                                                  SizedBox(width: 4.w),
                                                  Text(
                                                    drama.epNumTotal.toString(), // 播放量
                                                    style: TextStyle(color: Colors.white, fontSize: 10.sp),
                                                  ),
                                                ],
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                      Padding(
                                        padding: EdgeInsets.all(4.w), // 调整padding来缩小内容
                                        child: Text(
                                          drama.title,
                                          maxLines: 2,
                                          overflow: TextOverflow.ellipsis,
                                          style: TextStyle(fontWeight: FontWeight.bold, fontSize: 12.sp), // 调整字体大小
                                        ),
                                      ),
                                      Padding(
                                        padding: EdgeInsets.symmetric(horizontal: 4.w), // 调整padding来缩小内容
                                        child: Text(
                                          drama.desc,
                                          maxLines: 1,
                                          overflow: TextOverflow.ellipsis,
                                          style: TextStyle(fontSize: 10.sp), // 调整字体大小
                                        ),
                                      ),
                                    ],
                                  ),
                                );
                              },
                            );
                          } else {
                            return const Center(child: Text('No data available'));
                          }
                        },
                      );
                    }).toList(),
                  ),
                ),
              ),

            ),
          );
        } else {
          return Scaffold(
            appBar: AppBar(
              title: const Text('推荐'),
              backgroundColor: Colors.white,
              elevation: 0,
            ),
            body: const Center(child: Text('No tabs available')),
          );
        }
      },
    );
  }

  @override
  void dispose() {
    _tabController?.removeListener(_handleTabSelection);
    _tabController?.dispose();
    super.dispose();
  }
}

class VideoTab extends StatelessWidget {
  const VideoTab({super.key});

  @override
  Widget build(BuildContext context) {
    return Center(child: Text('视频内容'));
  }
}

class RecommendedTab extends StatelessWidget {
  const RecommendedTab({super.key});

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        childAspectRatio: 0.7,
        crossAxisSpacing: 10.w,
        mainAxisSpacing: 10.h,
      ),
      itemCount: _HomeScreenState.shortFilms.length,
      itemBuilder: (context, index) {
        final shortFilm = _HomeScreenState.shortFilms[index];
        return GestureDetector(
          onTap: () {
            // 处理点击事件
          },
          child: Card(
            margin: EdgeInsets.all(8.w),
            child: Column(
              children: [
                Expanded(
                  child: Image.network(
                    shortFilm.thumbnailUrl,
                    fit: BoxFit.cover,
                    errorBuilder: (BuildContext context, Object exception, StackTrace? stackTrace) {
                      return const Icon(
                        Icons.error,
                        size: 50,
                      );
                    },
                  ),
                ),
                Padding(
                  padding: EdgeInsets.all(8.w),
                  child: Text(
                    shortFilm.title,
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(fontSize: 14.sp, fontWeight: FontWeight.bold),
                  ),
                ),
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 8.w),
                  child: Text(
                    '${shortFilm.category} - ${shortFilm.episodes}集',
                    style: TextStyle(fontSize: 12.sp),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}